package com.supreme.commonrocketmq.config;

import com.supreme.commonrocketmq.config.props.RocketmqProps;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Slf4j
@Configuration
public class RocketmqConfig {

    @Resource
    private RocketmqProps rocketmqProps;

    @Bean(value = "exampleProducer")
    public DefaultMQProducer exampleProducer() {
        DefaultMQProducer producer = new DefaultMQProducer(rocketmqProps.getExample().getGroup());
        producer.setNamesrvAddr(rocketmqProps.getProducerNameSrv());
        producer.setVipChannelEnabled(true);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        return producer;
    }

    @Bean(value = "orderProducer")
    public DefaultMQProducer orderProducer() {
        DefaultMQProducer producer = new DefaultMQProducer(rocketmqProps.getOrder().getGroup());
        producer.setNamesrvAddr(rocketmqProps.getProducerNameSrv());
        producer.setVipChannelEnabled(true);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        return producer;
    }

    @Bean(value = "loggerProducer")
    public DefaultMQProducer loggerProducer() {
        String loggerGroup = rocketmqProps.getLogger().getGroup();
        DefaultMQProducer producer = new DefaultMQProducer(loggerGroup);
        producer.setNamesrvAddr(rocketmqProps.getProducerNameSrv());
        producer.setVipChannelEnabled(true);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        return producer;
    }

    @PreDestroy
    private void destroyRocketMQProducer() {
        exampleProducer().shutdown();
        orderProducer().shutdown();
        loggerProducer().shutdown();
    }
}
